package com.itheima.health.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;
import com.fasterxml.jackson.databind.ObjectMapper;


import java.io.IOException;
import java.util.List;

/**
 * @Author likepei
 * @Date 2020/4/4 23:04
 * @Version v1.0
 * @Description 移动端 套餐控制器
 */
@RestController
@RequestMapping("mobile/setmeal")
@Slf4j
public class SetmealController {

    //依赖注入
    @Reference
    private SetmealService setmealService;
    @Autowired
    private JedisPool jedisPool;


    /**
     * 基于套餐Id 获取指定的套餐对象
     * @param
     * @return
     */
    @RequestMapping("/getSetmeal")
    public Result getSetmeal() throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        //从redis数据库获取套餐信息
        String setmeals = jedisPool.getResource().get("套餐数据添加到redis数据库");
        //判断
        if (setmeals==null){
            //从数据库查询套餐信息
            setRedis();
        }

        setmeals=jedisPool.getResource().get("套餐数据添加到redis数据库");

        List<Setmeal> list = setmealService.findAll();

        String str = mapper.writeValueAsString(list);

        if (setmeals.equals(str)){
            return new Result(true, MessageConst.QUERY_SETMEALLIST_SUCCESS, list);
        }
        //将字符串转换成list对象
        List<Setmeal> setmealList = mapper.readValue(setmeals, List.class);
        //返回查询结果
        return new Result(true, MessageConst.QUERY_SETMEALLIST_SUCCESS, setmealList);

    }

    private void setRedis() throws JsonProcessingException {

        ObjectMapper mapper = new ObjectMapper();

        List<Setmeal> setmealList = setmealService.findAll();
        //将结果转换为json字符串
        String str = mapper.writeValueAsString(setmealList);
        //添加rids数据库的套餐列表
        jedisPool.getResource().set("套餐数据添加到redis数据库",str);
    }


    @RequestMapping("/findById")
    public Result findById(Integer id){
        Setmeal setmeal = setmealService.findById(id);
        return new Result(true,MessageConst.QUERY_SETMEAL_SUCCESS,setmeal);
    }
}

